﻿using BaseAuthRole.AspNetCore;
using BaseAuthRole.Domain.Input;
using BaseAuthRole.Domain.OutPut;
using BaseAuthRole.DTO.User;
using BaseAuthRole.IService;
using Coldairarrow.Util;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RS.BaseModel;
using RS.BaseModel.Common;
using RS.Environment;
using RS.Tool.Base;
using RS.Tool.DataBase;
using RS.Tool.Init;

namespace BaseAuthRole.Web.Controllers
{
    //[Route("[controller]/[action]")]
    public class HomeController : Controller
    {
        private IUserService _userService;

        public HomeController(IUserService userService)
        {
            this._userService = userService;
        }

        //[UserInfoCheckFilter]

        public ActionResult Index()
        {

            if (!string.IsNullOrEmpty(ConfigurationHelper.GetAppSettings("home_url")))
            {

                return Redirect(ConfigurationHelper.GetAppSettings("home_url"));

            }

            return View();

        }

        public ActionResult Login()
        {
            return PartialView();
        }
        //todo
        public ActionResult LoginOut()
        {

            //UserInfoHandler.ClearUserInfo("admin_user");
            //UserInfoHandler.ClearUserInfo();
            ViewData["return_url"] = "/Home/Login";
            // return Redirect(ResultHanlder.ErrorUrl(BaseTools.Model.Enum.EnumBaseResult.NoLogin));

            return PartialView();
        }

        [HttpGet]
        public ActionResult PassWordChange()
        {
            return PartialView();
        }

        #region 请求部分

        /// <summary>
        /// 生成 token 下发cookie
        /// </summary>
        /// <param name="loginDoInput"></param>
        /// <returns></returns>
        [HttpPost]
        public string LoginDo([FromForm] LoginDoInput loginDoInput)
        {

            var result = new CommonResult();

            var return_url = loginDoInput.ReturnUrl;


            if (string.IsNullOrEmpty(return_url))
            {
                return_url = "/Home/Index";
            }

            var r = this._userService.Login(loginDoInput.LoginName, loginDoInput.PassWord, loginDoInput.CodeToken, loginDoInput.VerifyCode);

            if (r.IsError)
            {

                return JsonConvert.SerializeObject(r);

            }

            //UserCookieHelper.SetCookieUserInfo(r.Result, DateTimeOffset.Now.AddHours(2));

            CookieHelper.SetCookie(r.Result, ConfigurationHelper.GetAppSettings("cookieUserKey"), DateTimeOffset.Now.AddHours(2), false);

            if (ConfigurationHelper.GetAppSettings("LoginEdisCookieWrite") == "1")
            {
                var userInfoResult = _userService.GetUserInfo(r.Result.Token);

                //写入当前页面的cookie
                var expireTime = DateTime.UtcNow.AddHours(10);
                var edis_ui = new BaseAuthRole.DTO.User.UserLoginInfo()
                {
                    authtoken = r.Result.Token,
                    Avatar = userInfoResult.Result.Avatar,
                    Company = userInfoResult.Result.Company,
                    Department = userInfoResult.Result.Department,
                    DepartmentId = userInfoResult.Result.DepartmentId,
                    Email = userInfoResult.Result.Email,
                    EmployeeType = userInfoResult.Result.EmployeeType,
                    FeiShuUid = userInfoResult.Result.FeiShuUid,
                    Gender = userInfoResult.Result.Gender,
                    IdCardNo = userInfoResult.Result.IdCardNo,
                    JobNumber = userInfoResult.Result.JobNumber,
                    JobState = userInfoResult.Result.JobState,
                    JobTitle = userInfoResult.Result.JobTitle,
                    Name = userInfoResult.Result.Name,
                    Nation = userInfoResult.Result.Nation,
                    Nationality = userInfoResult.Result.Nationality,
                    NationalityCode = userInfoResult.Result.NationalityCode,
                    NationPlace = userInfoResult.Result.NationPlace,
                    NickName = userInfoResult.Result.NickName,
                    Phone = userInfoResult.Result.Phone,
                    Profession = userInfoResult.Result.Profession,
                    Title = userInfoResult.Result.Title,
                    TopQualifications = userInfoResult.Result.TopQualifications,
                    Uid = userInfoResult.Result.Uid,
                    LoginName = userInfoResult.Result.LoginName
                };

                foreach (var action in userInfoResult.Result.Actions)
                {
                    if (action.Type == 0)
                    {
                        edis_ui.Actions.Add(action.ControlName);
                    }
                }

                HttpContext.Response.Cookies.Append("edis-ui", Newtonsoft.Json.JsonConvert.SerializeObject(edis_ui), new CookieOptions { Expires = expireTime });
                HttpContext.Response.Cookies.Append("uid", userInfoResult.Result.Uid, new CookieOptions { Expires = expireTime });
            }

            result.IsError = false;

            result.Result = return_url;

            return JsonConvert.SerializeObject(result);

        }

        [HttpPost]
        public string PwChange([FromForm] PwChangeInput pwChangeInput)
        {
            var result = new CommonResult();

            var a = pwChangeInput.LoginName;

            var password = SecretHelper.GetMD5(pwChangeInput.Password);

            var new_password = pwChangeInput.NewPassword;

            var new_password2 = pwChangeInput.NewPassword2;


            // var user = UUIUserIService.GetUIUser(login_name,password);

            object obj = null;


            if (RegHelper.CheckNum(a))
            {

                if (a.Length == 11)
                {
                    obj = new { Phone = a, PassWord = password };

                }
                else if (a.Length == 6)
                {
                    obj = new { JobNumber = a, PassWord = password };


                }
                else
                {
                    obj = new { LoginName = a, PassWord = password };

                }
            }
            else
            {

                obj = new { LoginName = a, PassWord = password };
            }


            var user = this._userService.GetUIUser(obj);

            if (user == null)
            {

                result.Message = "用户名或密码错误";

                return JsonConvert.SerializeObject(result);
            }


            if (new_password.Length < 6)
            {

                result.Message = "至少输入6位新密码";

                return JsonConvert.SerializeObject(result);

            }

            if (!string.Equals(new_password, new_password2))
            {

                result.Message = "两次输入密码不一致";

                return JsonConvert.SerializeObject(result);

            }


            user.PassWord = SecretHelper.GetMD5(new_password);

            var r = this._userService.UpdateUIUser(user);

            if (r > 0)
            {

                result.IsError = false;

            }
            else
            {

                result.Message = "操作失败";

            }

            return JsonConvert.SerializeObject(result);
        }
        #endregion

        [HttpGet]
        public ActionResult SSOCheck()
        {
            var user = new BaseUserLoginModel
            {
                Id = "001",
                IsAdmin = 1,
                Name = "管理员",
                AddTime = DateTime.UtcNow.AddHours(8)

            };

            UserCookieHelper.SetCookieUserInfo(user);

            return Redirect("/UserManager/Index");
        }

        [HttpGet]
        public async Task<ActionResult> GetVerifyCode()
        {
            var result = await _userService.GetVerifyCode();

            return Ok(result);
        }


        [HttpGet]
        public int Init()
        {

            var admin = new UUIUser
            {
                Id = "0",
                Name = "admin",
                LoginName = "admin",
                PassWord = SecretHelper.GetMD5("1qaz@2wsx,."),
                Status = 1,
                Phone = "0000"

            };
            var r = this._userService.AddUUIUser(admin);
            return r;
        }


        [HttpGet]
        public int AddEmployee() {

            var rd = new Random();
            var name = "供应商"+rd.Next(1, 100).ToString();
            var admin = new UUIUser
            {              
                Name = name,
                LoginName = name,
                PassWord = SecretHelper.GetMD5("1qaz@2wsx,."),
                Status = 1,
                Phone = "13012345678",
                 EmployeeType ="7",
                  Gender =1,
                   JobState=1
                    

            };
            var r = this._userService.AddUUIUser(admin);
            return r;
        }

    }
}
